package com.atguigu.srb.core.controller.api;

import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserIndexVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author javaCode
 * @since 2025-07-19
 */
@Api(tags = "会员接口")
@RestController
@RequestMapping(value = "/api/core/userInfo")
@RequiredArgsConstructor
public class UserInfoController {

    // 用户基本信息 服务类
    private final UserInfoService userInfoService;

    /**
     * 会员注册
     */
    @ApiOperation("会员注册")
    @PostMapping(value = "/register")
    public R register(@RequestBody RegisterVO registerVO) {
        // 注册
        this.userInfoService.register(registerVO);

        return R.ok().message("注册成功");
    }


    /**
     * 会员登录
     */
    @ApiOperation("会员登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody LoginVO loginVO, HttpServletRequest request) {

        String ip = request.getRemoteAddr();

        UserInfoVO userInfoVO = this.userInfoService.login(loginVO, ip);

        return R.ok().data("userInfo", userInfoVO);
    }

    /**
     * 校验令牌
     */
    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public R checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");

        boolean result = JwtUtils.validateToken(token);

        return result ? R.ok() : R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
    }

    /**
     * 校验手机号是否注册
     */
    @ApiOperation("校验手机号是否注册")
    @GetMapping("/checkMobile/{mobile}")
    public boolean checkMobile(@PathVariable("mobile") String mobile) {
        return userInfoService.checkMobile(mobile);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("auth/getIndexUserInfo")
    public R getIndexUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        UserIndexVO userIndexVO = userInfoService.getIndexUserInfo(userId);

        return R.ok().data("userIndexVO", userIndexVO);
    }
}
